package com.jose.photogallery;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.jose.photogallery.domain.PhotogalleryDAO;
import com.jose.photogallery.domain.Photo;

@SuppressWarnings("serial")
public class ServePhotoServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(ServePhotoServlet.class.getName());
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		// Parameters
		String blobKey = req.getParameter("key");
		
		PhotogalleryDAO dao = new PhotogalleryDAO();
		// Get the photo
		Photo photo = dao.getPhoto(blobKey);
		
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		
		if (user != null){
			String logoutUrl = userService.createLogoutURL("/");
			req.setAttribute("logoutUrl", logoutUrl);
			req.setAttribute("user", user);
		} else {
			String loginUrl = userService.createLoginURL("/");
			req.setAttribute("loginUrl", loginUrl);
		}
		
		if (photo != null){
			log.info("Show the photo with key=" + photo.getBlobKey());
			req.setAttribute("photo", photo);
			req.getRequestDispatcher("/WEB-INF/JSP/viewphoto.jsp").forward(req, resp);
		} else {
			req.setAttribute("error", "Sorry, this photo does not exists!");
			req.getRequestDispatcher("/WEB-INF/JSP/errorpage.jsp").forward(req, resp);
		}
	}
}
